<template>
  <div id="code-editor"
       ref="codeEditorRef"
       :style="{minHeight: props.height + 'px !important'}" />
</template>

<script setup lang="ts">
import * as monaco from "monaco-editor";
import { onMounted, ref, toRaw,  defineProps, defineEmits, withDefaults, watch } from "vue";

const codeEditorRef = ref();
const codeEditor = ref();
const emit = defineEmits(['editorCode']);
onMounted(() => {
  if (!codeEditorRef.value) {
    return;
  }
  // Hover on each property to see its docs!
  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: props.content ? props.content :  'import java.util.Scanner;\n' +
      'public class Main {\n' +
      '    public static void main(String[] args) {\n' +
      '        int a, b;\n' +
      '        Scanner scanner = new Scanner(System.in);\n' +
      '        a = scanner.nextInt();\n' +
      '        b = scanner.nextInt();\n' +
      '        System.out.println("a+b=" + (a+b));\n' +
      '    }\n' +
      '}',
    language: props.language,
    automaticLayout: true,
    colorDecorators: true,
    minimap: {
      enabled: true,
    },
    readOnly: false,
    theme: "vs-dark",
    // lineNumbers: "off",
    // roundedSelection: false,
    // scrollBeyondLastLine: false,
  });

  // 编辑 监听内容变化
  codeEditor.value.onDidChangeModelContent(() => {
    let codeValue = toRaw(codeEditor.value).getValue();
    emit('editorCode', codeValue);
  });
  // 将模版的初始值传给 父元素
  emit('editorCode', toRaw(codeEditor.value)?.getValue());
});
/**
 * 定义组件属性类型
 */
interface Props {
  language: string;
  content: string;
  height: number;
}
/**
 * 给组件指定初始值
 */
const props = withDefaults(defineProps<Props>(), {
  language: () => "",
  content: () => "",
  height: () => 690,
});
// 使用watch监视language变量
watch(
  () => props.language,
  () => {
    if (codeEditor.value) {
      monaco.editor.setModelLanguage(
        toRaw(codeEditor.value).getModel(),
        props.language
      );
    }
  }
);


const fillValue = () => {
  if (!codeEditor.value) {
    return;
  }
  // 改变值
  toRaw(codeEditor.value).setValue("新的值");
};
</script>

<style scoped>
#code-editor {
  margin-top: 10px;
}
</style>

